<template>
  <div :style="{'text-align': 'center','font-size':font_size,width:'1000px'}">
    <el-card shadow="never">
      <div style="font-size:2rem;font-weight:600;">
        <span>交易行 · {{ server }} · </span>
        <span :style="{color:item.color}">{{ item.name }}</span>
      </div>
      <el-row class="help-tip-card">
        <el-card style="width: 100%;margin: 0.2rem;">
          <el-row>
            <el-col :span="12">
              <el-row>
                <el-col class="primary-icon" :span="4">
                  <div>命令</div>
                  <div class="ver-line"></div>
                </el-col>
                <el-col :span="20">
                  <div class="primary-title">
                    <div>
                      <span style="color:#999">查看概要价格：</span>
                      <span>交易行 [服务器] 物品名称 [页码]</span>
                    </div>
                    <div>
                      <span style="color:#999">然后详细价格：</span>
                      <span>[序号]</span>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-col class="primary-icon" :span="4">
                  <div style="color: #999999;">说明</div>
                  <div class="ver-line"></div>
                </el-col>
                <el-col :span="20">
                  <div class="primary-content">
                    <div>1. 概要价格每天更新1次，详细价格每10分钟更新1次。</div>
                    <div>2. 一页默认显示20个物品，可以输入页码来选择不同页。</div>
                    <div>3. 每次访问将给物品人气+1，人气越高越靠前。</div>
                  </div>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-card>
      </el-row>
      <el-collapse v-model="expanded_items">
        <el-collapse-item name="1">
          <template #title>
            <div class="global-title">
              <span>基本信息</span>
              <span>（id:{{ item.id }}）</span>
            </div>
          </template>
          <el-row class="goods-info-card">
            <el-col :span="8" style="border: solid 1px #cccccc;padding:0.5rem;margin: 0.5rem;">
              <el-row>
                <el-col :span="4">
                  <img :src="item.img_url" :style="{height: '3rem'}" />
                </el-col>
                <el-col :span="20" style="text-align: left;">
                  <div>
                    <span class="sub-title">名称</span>
                    <span :style="{'font-size':font_size,color:item.color,'margin-left':'0.5rem'}">
                      <span>{{ item.name }}</span>

                    </span>
                  </div>
                  <div>
                    <span class="sub-title">热度</span>
                    <el-rate :model-value="convertPop(item.u_popularity)" disabled show-score text-color="#cccccc" />
                  </div>
                </el-col>
              </el-row>
              <el-row v-if="item.level || (item_attributes && item_attributes.length)">
                <el-row v-if="item.level">
                  <div style="margin-right:1rem">
                    <span class="sub-title">品质</span>
                    <span>{{ item.level }}</span>
                  </div>
                  <div>
                    <span class="sub-title">最大耐久</span>
                    <span>{{ item.maxDurability }}</span>
                  </div>
                </el-row>
                <el-row v-if="item_attributes && item_attributes.length">
                  <span class="sub-title">特性</span>
                  <span style="text-align: left;">
                    <el-tree :data="item_attributes">
                      <template #default="{ node, data }">
                        <span :style="{color:data.color}">{{ data.label }}</span>
                      </template>
                    </el-tree>
                  </span>
                </el-row>
              </el-row>

              <el-row v-else-if="wucai_desc" style="display: block">
                <el-row>
                  <div style="margin-right:1rem">
                    <span class="sub-title">五彩石</span>
                    <span>{{ wucai_desc.brief.join('|') }}</span>
                  </div>
                </el-row>
                <el-row>
                  <span class="sub-title">属性</span>
                  <span style="text-align: left;">
                    <el-tree v-for="(prop,index) in wucai_desc.props" :key="index" :data="prop">
                      <template #default="{ node, data }">
                        <span style="color:#38b48b;margin-right:0.5rem;">{{ data.v[0].join('+') }}</span>
                        <span style="color:#7b7c7d">{{
                          data.f.map(x=>`${x[0]}>=${x[1]}`).join('|')
                          }}</span>
                      </template>
                    </el-tree>
                  </span>
                </el-row>
              </el-row>
            </el-col>
            <el-col :span="14" style="border: solid 1px #cccccc;padding:0.5rem;margin: 0.5rem;">
              <el-divider content-position="left">更多信息</el-divider>
              <el-row>
                <span class="sub-title">标签</span>
                <el-tag v-if="item.typeLabel" type="danger">{{ item.typeLabel }}</el-tag>
                <div v-else>无</div>
              </el-row>
              <el-row style="text-align: left;">
                <span class="sub-title">描述</span>
                <span>
                  <div v-for="(x,index) in item_description" :key="index" style="width: 500px;">{{ x }}</div>
                </span>
              </el-row>
              <el-row>
                <div>
                  <span class="sub-title">回收价</span>
                  <span v-if="item.recovery_price">
                    <span>{{ convertGold(item.recovery_price)[0] }}</span>
                    <img :src="convertGold(item.recovery_price)[1]" />
                  </span>
                  <span v-else>杂货商不收</span>
                </div>
              </el-row>
              <el-row v-if="item.maxExistAmount">
                <div>
                  <span class="sub-title">最大拥有数</span>
                  <span>{{ item.maxExistAmount }}</span>
                </div>
              </el-row>

              <el-row>
                <div>
                  <span class="sub-title">绑定类型</span>
                  <span>{{ item.bind_type_str }}</span>
                </div>
              </el-row>
            </el-col>
          </el-row>
        </el-collapse-item>
        <el-collapse-item name="2">
          <template #title>
            <div class="global-title">
              <span style="margin-right:1rem;">实时价格</span>
              <span v-if="P_detail.price_lowest" style="margin-right:1rem;">
                <span>底价</span>
                <span v-if="P_detail.price_lowest == P_detail.price_valid">(有效)</span>
                <span>{{ convertGold(P_detail.price_lowest)[0] }}</span>
                <img :src="convertGold(P_detail.price_lowest)[1]" />
              </span>
              <span v-if="P_detail.price_valid && P_detail.price_lowest != P_detail.price_valid">
                <span>有效底价</span>
                <span>{{ convertGold(P_detail.price_valid)[0] }}</span>
                <img :src="convertGold(P_detail.price_valid)[1]" />
              </span>
            </div>
          </template>
          <el-row class="goods-current-price">
            <div v-if="P_detail.prices && P_detail.prices.length" class="detail-price-container">
              <div v-for="(x,index) in P_detail.prices" :key="index" class="detail-price-single-card">
                <div class="detail-price-title">
                  <span>数量</span>
                  <span>{{ convertSci(x[1]) }}</span>
                  <span>({{ formatTime(x[0] * 1e3) }})</span>
                </div>
                <div class="detail-price-value">
                  <span>{{ convertGold(x[2])[0] }}</span>
                  <img :src="convertGold(x[2])[1]" />
                </div>
                <div class="detail-price-description">
                  <div>{{ parseTime(x[0] * 1e3) }}</div>
                </div>
              </div>
            </div>
            <el-empty v-else style="margin:auto" description="没有内容" />
          </el-row>
        </el-collapse-item>
        <el-collapse-item name="3">
          <template #title>
            <div class="global-title">价格趋势</div>
          </template>
          <el-row class="goods-price-trend">
            <div id="chart-goods-price-trend" style="height:400px;width:1000px"></div>
          </el-row>
          <el-row class="goods-price-trend">
            <div id="chart-goods-price-low-trend" style="height:400px;width:1000px"></div>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </el-card>
  </div>

</template>

<style lang="scss">
  .ver-line {
    height: 3rem;
    border: 1px solid #aaaaaa;
  }

  .primary-icon {
    font-weight: 600;
    font-size: 1.2rem;
    line-height: 1.4rem;
    display: flex;
    justify-content: space-evenly;
  }

  .primary-title {
    color: #ff0000;
    font-weight: 400;
    text-align: left;
    line-height: 1.4rem;
    font-size: 1.12rem;
  }

  .primary-content {
    color: #999;
    text-align: left;
    line-height: 1rem;
    font-size: 0.8rem;
  }

  .sub-title {
    margin-right: 0.5rem;
    font-weight: 600;
  }

  .global-title {
    font-weight: 600;
    font-size: 1.2rem;
  }
</style>


<style lang="scss">
  .detail-price-container {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }

  .detail-price-single-card {
    overflow: hidden;
    white-space: nowrap;
    margin: 0.2rem;
    background: #4ce6ff;
    font-size: 1.2rem;
    max-width: 15rem;
    min-width: 10rem;
    border-radius: 0.5rem;
    color: #ffffff;
    box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 1);
  }

  .detail-price-title {
    background: #0490e1;
    font-size: 1rem;
  }

  .detail-price-value {
    color: #1f0000;
    text-shadow: 0 1px #000, 1px 0 #000, -1px 0 #000, 0 -1px #000;
  }

  .detail-price-description {
    font-size: 0.8rem;
  }
</style>
<script>
  const { defineComponent, reactive, toRefs, ref, onMounted, computed } = Vue
  const component = defineComponent({
    name: 'SPAComponent',
    components: {},
    setup () {
      const methods = {
        parseTime,
        formatTime,
        convertGold,
        convertSci,
        convertPop
      }
      // const price_handle = ['AvgPrice','LowestPrice','HighestPrice']
      const price_logs_converted = (field_name) => {
        const raw = params_data.price_logs
        const result = []
        let min_price = 10000 * 1e4 // 默认以砖计算
        raw.sort((a, b) => new Date(a.Date) - new Date(b.Date))
        raw.map(x => {
          const v = x[field_name]
          if (v < min_price && v > 0) min_price = v
        })
        const icon = convertGold(min_price)
        raw.map(x => {
          let v = x[field_name] / icon[2] // 转换为标准值
          v = Math.ceil(v * 100) / 100
          result.push(Object.assign(x, { [field_name]: v }))
        })
        return [result, icon[1]]
      }

      const init_single_chart = (chart_element, chart_data_name, seriesName) => {
        const [avg_logs, avg_icon] = price_logs_converted(chart_data_name)
        const chart = echarts.init(document.getElementById(chart_element))
        const option = {
          animation: false,
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            boundaryGap: false
          },
          yAxis: [],
          series: []
        }
        appendSeriesYAxisItem({
          option,
          index: 0,
          seriesName,
          data: avg_logs.map(x => [x.Date, x[chart_data_name]]),
          series_option: {
            label: { show: true },
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            },
            smooth: true,
          },
          yAxis_option: {
            scale: true,
            nameTextStyle: {
              rich: {
                a: {},
                b: { backgroundColor: { image: avg_icon }, height: 25 }
              }
            }
          }
        })
        appendSeriesYAxisItem({
          option,
          index: 1,
          seriesName: '数量',
          data: avg_logs.map(x => [x.Date, x.SampleSize]),
          series_option: {
            label: {
              show: true,
              formatter: value => {
                v = convertSci(value.data[1])
                return v
              }
            },
            smooth: true,
          },
          yAxis_option: {
            scale: true,
          },
        })
        chart.setOption(option)
      }
      methods.init_chart_trend = () => {
        init_single_chart('chart-goods-price-trend', 'AvgPrice', '{a|均价 / 单位}{b|}')
        init_single_chart('chart-goods-price-low-trend', 'LowestPrice', '{a|底价 / 单位}{b|}')
      }
      onMounted(() => {
        methods.init_chart_trend()
      })



      const item_description = computed(() => {
        let v = params_data.item.desc
        if (!v) return ['暂时还没有任何信息']
        v = v.toLowerCase()
        v = v.replaceAll('<text>', '')
        v = v.replaceAll('</text>', '')
        v = v.replaceAll('\\n', '')
        v = v.replaceAll('\\', '')
        v = v.replace(/font\=\d*/g, '')
        let result = v.match(/text="[^ \f\n\r\t\v!"]*"/gm)
        result = result || [v]
        return result.map(x => x.substring(6, x.length - 1))
      })
      const item_attributes = computed(() => {
        const v = params_data.item.attributes
        if (!v) return []
        const color_dict = {
          'green': '#00c848',
          'white': '#000000'
        }
        v.map(x => {
          // 更改游戏颜色
          if (color_dict[x.color]) x.color = color_dict[x.color]
          x.children = [{ label: 'x' }] // 为了显示icon
        })
        return v
      })
      const wucai_desc = computed(() => {
        const properties = params_data.item.wucai_properties
        if (!properties || !properties.length) return null
        const brief = properties.map(x => x.values.map(x1 => x1[0]).join('|'))
        const r = {
          brief,
          props: properties.map(x => {
            const f = x.filters
            const v = x.values
            return [{ label: v.map(x => x[0]).join('|'), v, f, children: [{}] }]
          })
        }
        return r
      })
      const P_detail = computed(() => {
        const p = params_data.price_detail
        if (!p) return {}
        if (!p.prices) {
          p.prices = []
          return p
        }
        const result = [] // 针对价格实施去重，发现价格变化少于0.01%则合并
        let last = -1
        p.prices.map(x => {
          const cur = x[2]
          if (last <= 0 || Math.abs((cur - last) / last) > 1e-4) {
            last = cur
            result.push(x)
          }
        })
        p.prices = result
        return p
      })
      const expanded_items = reactive(['1', '2', '3'])
      return {
        item: {}, // 物品详情
        server: '', // 唯我独尊
        price_detail: {}, // 当前实时价格详情
        price_logs: [], // 价格历史
        item_description,
        item_attributes,
        price_logs_converted,
        wucai_desc, // 五彩石属性
        P_detail, // 处理后的详细价格
        expanded_items,
        ...methods,
      }
    },
  })
</script>